package com.zxt.recruit.Controller.Upload;

import com.zxt.recruit.model.SysUploadImgInfo;
import com.zxt.recruit.model.vo.RestBean;
import com.zxt.recruit.service.impl.SysUploadImgInfoServiceImpl;
import com.zxt.recruit.util.ImageUtil;
import com.zxt.recruit.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

//上传 附件/图片等本地上传
@RequestMapping("/api/upload")
@RestController
@Slf4j
public class UploadController {

    @Value("${img.position}")
    String imgPosition;

    @Value("${resource.position}")
    String resourcePosition;

    @Value("${location.port}")
    String serverAddress;

    @Resource
    SysUploadImgInfoServiceImpl sysUploadImgInfoService;

    @Resource
    JwtUtil  jwtUtil;

    @RequestMapping("/file")
    public RestBean simpleUpLoad(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        SysUploadImgInfo uploadImgInfo=new SysUploadImgInfo();
        String jwtUUID = jwtUtil.getJwtUUID(request);
        try {
            if (file.isEmpty()) {
                return RestBean.failure(400, "上传的文件为空");
            }
            String originalFileName = file.getOriginalFilename();
            if (originalFileName == null || originalFileName.isEmpty()) {
                return RestBean.failure(400, "文件名无效");
            }
            String newFileName = UUID.randomUUID()+ originalFileName.substring(originalFileName.lastIndexOf("."));
            String filePath = resourcePosition + UUID.randomUUID()+ originalFileName.substring(originalFileName.lastIndexOf("."));
            File directory = new File(resourcePosition);
            if (!directory.exists() && (!directory.mkdirs())) {
                return RestBean.failure(500, "文件夹初始化失败");
            }
            String url = serverAddress + "/img/" + newFileName;
            uploadImgInfo.setImgName(originalFileName);
            uploadImgInfo.setImgSize((double) file.getSize());
            uploadImgInfo.setInputTime(LocalDateTime.now());
            uploadImgInfo.setUserId(jwtUUID);
            uploadImgInfo.setImgHref(url);
            sysUploadImgInfoService.save(uploadImgInfo);//保存上传信息
            file.transferTo(new File(filePath));
            return RestBean.success(url);
        } catch (IOException e) {
            return RestBean.failure(500, "文件保存失败");
        }
    }


    @PostMapping("/img")
    public RestBean uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            SysUploadImgInfo uploadImgInfo=new SysUploadImgInfo();
            String jwtUUID = jwtUtil.getJwtUUID(request);
            if (file.isEmpty()) {
                return RestBean.failure(400, "上传的文件为空");
            }
            String originalFileName = file.getOriginalFilename();
            uploadImgInfo.setImgName(originalFileName);
            if (originalFileName == null || originalFileName.isEmpty()) {
                return RestBean.failure(400, "文件名无效");
            }
            // 获取文件后缀名
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            // 生成UUID
            String uuid = UUID.randomUUID().toString();
            String originImg=imgPosition+"origin:"+uuid+fileExtension;

            // 构造文件名
            String newFileName = uuid + fileExtension;
            // 构造完整的文件保存路径
//            String directoryPath = "D:\\upload\\file\\img\\";
            uploadImgInfo.setImgSize((double) file.getSize());
            uploadImgInfo.setInputTime(LocalDateTime.now());
            uploadImgInfo.setUserId(jwtUUID);
            String filePath = imgPosition + newFileName;
            File directory = new File(imgPosition);
            if (!directory.exists() && (!directory.mkdirs())) {
                return RestBean.failure(500, "文件夹初始化失败");
            }
//            file.transferTo(new File(filePath));
//            String originImg="origin:"+filePath;
            file.transferTo(new File(originImg));
            ImageUtil.imgScale(originImg,filePath,0.6);
//            log.info("文件保存成功，路径：" + filePath);//该图像的存储地址
            String url = serverAddress + "/img/" + newFileName;
//            log.info("http://" + serverAddress + "/img/" + newFileName);//该图像的访问地址
            uploadImgInfo.setImgHref(url);
            sysUploadImgInfoService.save(uploadImgInfo);//保存上传信息
            return RestBean.success(url);
        } catch (IOException e) {
            log.error("文件保存失败：{}", e.getMessage());
            return RestBean.failure(500, "文件保存失败");
        }
    }
}
